package au.com.bus4u.service.impl;

import au.com.bus4u.dao.DaoSupport;
import au.com.bus4u.exception.ServiceException;
import au.com.bus4u.service.AuctionService;
import au.com.bus4u.service.UserService;
import au.com.bus4u.utils.DateUtil;
import au.com.bus4u.utils.EmailUtil;
import au.com.bus4u.utils.PageData;
import au.com.bus4u.utils.UuidUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.sound.midi.Soundbank;
import java.util.*;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private DaoSupport daoSupport;
    private String mapper = "UserMapper.";

    @Autowired
    private AuctionService cuctionService;

    @Transactional
    @Override
    public int save(PageData pd) throws Exception {


        checkUserInfo(pd);//验证必填项

        //注册验证用户是否已存在
        PageData findPhone = new PageData();
        findPhone.put("phone",pd.get("phone"));
        List<PageData> list = (List<PageData>) daoSupport.findForList(mapper+"list",findPhone);
        if(list.size() > 0 ){
            throw new ServiceException("用户注册异常:用户名已存在");
        }
        //补全数据库用户默认资料
        String user_id = UuidUtil.get32UUID();
        pd.put("user_id", user_id);
        pd.put("status", 2);//0-有效 1-冻结 2-邮箱未激活(默认注册必须强制验证邮箱才能算注册完成)
        pd.put("create_time", new Date());
        pd.put("create_ip", pd.getIpAddress());//请求IP


        pd.put("guest_credit_point",0);//积分 游客消费金额/积分(能根据活动增减)
        pd.put("guest_credit_point_all",0);//累积积分 游客消费金额/积分(只增不减) 对应旧系统memmber_sum_credit字段
        pd.put("guest_credit_earned",0);//游客信用 由司机对游客的评价
        pd.put("cust_level","Bronze");//会员等级名称
        pd.put("guest_rate_discount",1.0);//利率折扣 会员等级 打折级别 折扣 默认1   100%  根据积分而来


        //验证角色 普通注册只能注册3-承运商 4-司机 5-游客
//        System.err.println("UserServiceImpl.save:"+pd.get("role_id"));
        int role_id = Integer.parseInt(pd.get("role_id").toString());
//        System.err.println("role_id = " + role_id);
        if(!(role_id == 3 || role_id == 4 || role_id == 5)){
            throw new ServiceException("用户注册异常:无效的role_id");
        }

        //密码加密
        String salt = UuidUtil.get32UUID();
        pd.put("salt", salt);
        pd.put("password", getMd5Password(pd.get("password").toString(), salt));

        //根据角色ID 分别提取对应角色数据执行修改
        int count = 0;
        //UserCarrierMapper  UserDriverMapper  UserGuestMapper
        switch(role_id) {
            case 1:
                //SuperAdmin-超级管理员;
                break;
            case 2:
                //Admin-管理员;
                break;
            case 3:
                //Carrier-承运商;
                PageData carrier = new PageData();
                carrier.put("carrier_id",user_id);
                carrier.put("user_id",user_id);
                carrier.put("server_credit_point",0);//承运商的积分
                carrier.put("server_credit_earned",0);//游客信用 由承运商、司机对游客的评价
                count = (int) daoSupport.save("UserCarrierMapper.save", carrier);
                break;
            case 4:
                //Driver-司机;
                PageData driver = new PageData();
                driver.put("driver_id",user_id);
                driver.put("user_id",user_id);
                driver.put("server_credit_point",0);//司机的积分
                driver.put("server_credit_earned",0);//游客信用 由司机对游客的评价
                count = (int) daoSupport.save("UserDriverMapper.save", driver);
                break;
            /*case 5:
                //Guest-游客;
                PageData guest = new PageData();
                guest.put("guest_id",user_id);
                guest.put("user_id",user_id);
                guest.put("credit_point",0);
                guest.put("credit_point_all",0);
                guest.put("credit_earned",0);
                guest.put("rate_discount",1);
                guest.put("rate_discount",1);
                count = (int) daoSupport.save("UserGuestMapper.save", guest);
                break;
            default:
                //...;
                break;*/
        }
//        System.err.println("新增附加数据条数:"+count);
//        System.err.println("新注册用户数据:"+pd);
        return (int) daoSupport.save(mapper+"save", pd);
    }

    @Transactional
    @Override
    public int delete(String user_id) throws Exception {
//        System.err.println("UserServiceImpl.delete");
        PageData pd = new PageData();
        pd.put("user_id",user_id);
        pd = (PageData)daoSupport.findForObject(mapper+"list",pd);
//        System.err.println("pd = " + pd);
        if(pd == null){
            throw new ServiceException("删除失败:user_id:"+user_id+",查无此数据!");
        }

        int role_id = Integer.parseInt(pd.get("role_id").toString());
        int count = 0;
        //根据角色ID 分别提取对应角色数据执行修改
        //UserCarrierMapper  UserDriverMapper  UserGuestMapper
        switch(role_id) {
            case 1:
                //SuperAdmin-超级管理员;
                break;
            case 2:
                //Admin-管理员;
                break;
            case 3:
                //Carrier-承运商;
                count = (int) daoSupport.delete("UserCarrierMapper.delete", pd);
                break;
            case 4:
                //Driver-司机;
                count = (int) daoSupport.delete("UserDriverMapper.delete", pd);
                break;
            case 5:
                //Guest-游客;
                count = (int) daoSupport.delete("UserGuestMapper.delete", pd);
                break;
            default:
                //...;
                break;
        }
//        System.err.println("删除附加数据条数:"+count);
        return (int) daoSupport.delete(mapper+"deleteById", pd);
    }

    /**
     * 修改个人信息 不包含修改密码
     * @param pd
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public int edit(PageData pd) throws Exception {
//        System.err.println("UserServiceImpl.edit:start");
//        System.err.println("pd = [" + pd + "]");

        //将前端传递来的带中括号“[]”的参数去掉
        Set<String>  keySet = pd.keySet();
        Iterator<String> it = keySet.iterator();
        List<String> oldStr = new ArrayList<>();
        List<String> newStr = new ArrayList<>();
        while (it.hasNext()) {
            String str = it.next();
            String[] split = str.split("\\[");
            if(split.length > 1){
//                System.err.println(str);
                oldStr.add(str);
                String substring = split[1].substring(0, split[1].length() - 1);
//                System.err.println(substring);
                newStr.add(substring);
            }
        }

        for (int i = 0; i < oldStr.size(); i++ ){
//            System.err.println(oldStr.get(i));
//            System.err.println(newStr.get(i));
            pd.put(newStr.get(i),pd.get(oldStr.get(i)));
            pd.remove(oldStr.get(i));
        }

//        System.err.println("转换后数据");
//        System.err.println("pd = [" + pd + "]");


        if(pd.get("user_id") ==null || "".equals(pd.get("user_id").toString())  ){
            throw new ServiceException("修改异常:user_id不能空");
        }
        PageData currentUser = getCurrentUser();
        if(currentUser == null){
            throw new ServiceException("修改异常:用户未登陆");
        }
        String user_id_Session = getCurrentUserID();
        String user_id = pd.get("user_id").toString();
//        System.err.println("user_id_Session = " + user_id_Session);
//        System.err.println("user_id = " + user_id);

        if(pd.get("password") ==null || "".equals(pd.get("password").toString())  || pd.get("password").toString().length() == 32 ){
//            throw new ServiceException("修改异常:password不能空");
            //如果修改的时候密码为null 或 “” 空字符串 或 字符串长度为32则为密文密码 ，则移除password和salt 不执行修改密码
            pd.remove("password");
            pd.remove("salt");
        }else{
            //如果密码不为空 且字符串长度不为32 则执行密码加密保存数据
            String salt = UuidUtil.get32UUID();//重新更好新的盐值
            String password = pd.get("password").toString();
            pd.put("password",getMd5Password(password, salt));
            pd.put("salt",salt);
        }



        if(pd.get("user_email") ==null || "".equals(pd.get("user_email").toString()) || currentUser.getString("user_email").equals(pd.get("user_email").toString()) ){
            pd.remove("user_email");
        }else{
            //如果要修改邮箱需 触发按钮点击调用接口 发送验证码到新邮箱 再匹配新邮箱内的校验码 如果不匹配则remove 匹配成功再执行修改邮箱
//            System.err.println("流程待客户确认:");
//            System.err.println("如果要修改邮箱需 触发按钮点击调用接口 发送验证码到新邮箱 再匹配新邮箱内的校验码 如果不匹配则remove 并跑出异常提示信息;若匹配成功再执行修改邮箱");
        }


        if(pd.get("phone") ==null ||  "".equals(pd.get("phone").toString()) ){
            pd.remove("phone");
        }
        /*if( pd.get("sex") ==null || "".equals(pd.get("sex").toString())){
            pd.remove("sex");
        }*/
        if( pd.get("avatar") ==null|| "".equals(pd.get("avatar").toString()) ){
            pd.remove("avatar");
        }

        pd.put("update_time",new Date());


        //移除修改功能不能进行修改的字段
        pd.remove("create_time");
        pd.remove("create_ip");
        pd.remove("server_credit_point");
        pd.remove("server_credit_earned");
        pd.remove("guest_credit_point");
        pd.remove("guest_credit_point_all");
        pd.remove("guest_credit_earned");
        pd.remove("cust_level");
        pd.remove("guest_rate_discount");

        //转换日期格式
//        if(pd.get("carrier_lic_expired") ==null ||  "".equals(pd.get("carrier_lic_expired").toString()) ){
//            pd.remove("carrier_lic_expired");
//        }else{
//            Date carrier_lic_expired = DateUtil.formatString(pd.get("carrier_lic_expired").toString(), "yyyy-MM-dd");
//            System.err.println("carrier_lic_expired = " + carrier_lic_expired);
//            pd.put("carrier_lic_expired",carrier_lic_expired);
//        }



//        System.err.println("role_id="+pd.get("role_id"));
        int role_id = Integer.parseInt(pd.get("role_id").toString());
        int count = 0;
        //根据角色ID 分别提取对应角色数据执行修改
        //UserCarrierMapper  UserDriverMapper  UserGuestMapper

        //从session中获取当前登录用户的user_id，防止非管理人员利用bug方式修改其他人的信息
        switch(role_id) {
            case 1:
                //SuperAdmin-超级管理员;
                break;
            case 2:
                //Admin-管理员;
                break;
            case 3:
                //Carrier-承运商;
//                System.err.println("承运商保存1");
                if(!user_id.equals(user_id_Session) ){
                    throw new ServiceException("修改失败:您无权限修改他人数据!");
                }

                if(pd.get("carrier_lic_expired") ==null ||  "".equals(pd.get("carrier_lic_expired").toString()) ){
                    pd.remove("carrier_lic_expired");
                }else{
                    String carrier_lic_expired = pd.get("carrier_lic_expired").toString();//执照过期日
                    Date carrier_lic_expired_date = DateUtil.formatString(carrier_lic_expired, "yyyy-MM-dd");
                    pd.put("carrier_lic_expired",carrier_lic_expired_date);
                }

                count = (int) daoSupport.update("UserCarrierMapper.edit", pd);
                break;
            case 4:
                //Driver-司机;
                if(!user_id.equals(user_id_Session) ){
                    throw new ServiceException("修改失败:您无权限修改他人数据!");
                }
//                pd.put("user_id",user_id_Session);
//                System.err.println(pd.get("driver_lic_expired"));

                if(pd.get("car_fuel") ==null ||  "".equals(pd.get("car_fuel").toString()) ){
                    pd.remove("car_fuel");
                }
                if(pd.get("car_cost") ==null ||  "".equals(pd.get("car_cost").toString()) ){
                    pd.remove("car_cost");
                }
                if(pd.get("car_km") ==null ||  "".equals(pd.get("car_km").toString()) ){
                    pd.remove("car_km");
                }


                if(pd.get("driver_lic_expired") ==null ||  "".equals(pd.get("driver_lic_expired").toString()) ){
                    pd.remove("driver_lic_expired");
                }else{
                    String driver_lic_expired = pd.get("driver_lic_expired").toString();//执照过期日
                    Date driver_lic_expired_date = DateUtil.formatString(driver_lic_expired, "yyyy-MM-dd");
                    pd.put("driver_lic_expired",driver_lic_expired_date);
                }

                if(pd.get("bus_driver_lic_expired") ==null ||  "".equals(pd.get("bus_driver_lic_expired").toString()) ){
                    pd.remove("bus_driver_lic_expired");
                }else{
                    String bus_driver_lic_expired = pd.get("bus_driver_lic_expired").toString();//大巴车驾照 证件过期日
                    Date bus_driver_lic_expired_date = DateUtil.formatString(bus_driver_lic_expired, "yyyy-MM-dd");
                    pd.put("bus_driver_lic_expired",bus_driver_lic_expired_date);
                }

                if(pd.get("insur_expired") ==null ||  "".equals(pd.get("insur_expired").toString()) ){
                    pd.remove("insur_expired");
                }else{
                    String insur_expired = pd.get("insur_expired").toString();//保险过期日
                    Date insur_expired_date = DateUtil.formatString(insur_expired, "yyyy-MM-dd");
                    pd.put("insur_expired",insur_expired_date);
                }
//                System.err.println("司机数据");
//                System.err.println(pd);
                count = (int) daoSupport.update("UserDriverMapper.edit", pd);
                break;
            case 5:
                //Guest-游客;
                if(!user_id.equals(user_id_Session) ){
                    throw new ServiceException("修改失败:您无权限修改他人数据!");
                }
//                pd.put("user_id",user_id_Session);


                count = (int) daoSupport.update("UserGuestMapper.edit", pd);
                break;
            default:
                //...;
                break;
        }
//        System.err.println("修改附加数据条数:"+count);

//        System.out.println("UserServiceImpl.edit:end");
        return (int) daoSupport.update(mapper+"edit", pd);
    }

    @Override
    public int editDriverByUserID(PageData pd) throws Exception {
        checkDriverInfo(pd);
        return (int) daoSupport.update("UserDriverMapper.edit", pd);
    }

    @Override
    public int editCarrierByUserID(PageData pd) throws Exception {
        checkCarrierInfo(pd);
        return (int) daoSupport.update("UserCarrierMapper.edit", pd);
    }

    @Override
    public int editStatusById(PageData pd) throws Exception {

        if( pd.get("user_id") ==null ||"".equals(pd.get("user_id").toString())){
            throw new ServiceException("user_id不能空");
        }
        if(pd.get("status") ==null || "".equals(pd.get("status").toString())  ){
            throw new ServiceException("status不能空");
        }

        PageData data = new PageData();
        data.put("user_id",pd.get("user_id"));
        data.put("status",pd.get("status"));

        return (int) daoSupport.update(mapper+"edit", data);
    }

    @Override
    public List<PageData> list(PageData pd) throws Exception {

        //过滤null和空字符串搜索条件
        filterUserSearchData(pd);

        return (List<PageData>) daoSupport.findForList(mapper+"list",pd);
    }

    private void filterUserSearchData(PageData pd)  throws Exception {
        if(pd.get("user_id") == null || "".equals(pd.get("user_id"))){
            pd.remove("user_id");
        }

        if(pd.get("status") == null || "".equals(pd.get("status"))){
            pd.remove("status");
        }

        if(pd.get("old_status") == null || "".equals(pd.get("old_status"))){
            pd.remove("old_status");
        }

        if(pd.get("avatar") == null || "".equals(pd.get("avatar"))){
            pd.remove("avatar");
        }

        if(pd.get("phone") == null || "".equals(pd.get("phone"))){
            pd.remove("phone");
        }

        if(pd.get("user_email") == null || "".equals(pd.get("user_email"))){
            pd.remove("user_email");
        }

        if(pd.get("role_id") == null || "".equals(pd.get("role_id"))){
            pd.remove("role_id");
        }

        if(pd.get("suburb") == null || "".equals(pd.get("suburb"))){
            pd.remove("suburb");
        }

        if(pd.get("contact_num") == null || "".equals(pd.get("contact_num"))){
            pd.remove("contact_num");
        }

        if(pd.get("sex") == null || "".equals(pd.get("sex"))){
            pd.remove("sex");
        }

        if(pd.get("age") == null || "".equals(pd.get("age"))){
            pd.remove("age");
        }

        if(pd.get("post_code") == null || "".equals(pd.get("post_code"))){
            pd.remove("post_code");
        }

        if(pd.get("guest_credit_point") == null || "".equals(pd.get("guest_credit_point"))){
            pd.remove("guest_credit_point");
        }

        if(pd.get("guest_credit_point_all") == null || "".equals(pd.get("guest_credit_point_all"))){
            pd.remove("guest_credit_point_all");
        }

        if(pd.get("guest_credit_earned") == null || "".equals(pd.get("guest_credit_earned"))){
            pd.remove("guest_credit_earned");
        }

        if(pd.get("cust_level") == null || "".equals(pd.get("cust_level"))){
            pd.remove("cust_level");
        }

        if(pd.get("guest_rate_discount") == null || "".equals(pd.get("guest_rate_discount"))){
            pd.remove("guest_rate_discount");
        }

        if(pd.get("create_ip") == null || "".equals(pd.get("create_ip"))){
            pd.remove("create_ip");
        }
        if(pd.get("last_login_ip") == null || "".equals(pd.get("last_login_ip"))){
            pd.remove("last_login_ip");
        }




        if(pd.get("create_time_select") == null || "".equals(pd.get("create_time_select"))){
            pd.remove("create_time_select");
        }else{
            //拆分时间范围到搜索条件
            splitRangeTimeAndPushToSearch(pd,"create_time_select","yyyy-MM-dd HH:mm:ss","create_time_start","create_time_end");
        }

        if(pd.get("update_time_select") == null || "".equals(pd.get("update_time_select"))){
            pd.remove("update_time_select");
        }else{
            //拆分时间范围到搜索条件
            splitRangeTimeAndPushToSearch(pd,"update_time_select","yyyy-MM-dd HH:mm:ss","update_time_start","update_time_end");
        }


        if(pd.get("last_login_time_select") == null || "".equals(pd.get("last_login_time_select"))){
            pd.remove("last_login_time_select");
        }else{
            //拆分时间范围到搜索条件
            splitRangeTimeAndPushToSearch(pd,"last_login_time_select","yyyy-MM-dd HH:mm:ss","last_login_time_start","last_login_time_end");
        }

    }

    @Override
    public List<PageData> driverList(PageData pd) throws Exception {
        pd.put("role_id",4);
//        System.err.println("pd = " + pd);
        boolean searchType = checkDriverInfo(pd);//司机搜索条件非空过滤
//        System.err.println("pd = " + pd);

        List<PageData> list = new ArrayList<>();
                //搜索条件非空判断 并根据是否有司机指定字段来判断 是以用户 还是司机表来作为基表查询
        if(searchType){
            list = (List<PageData>) daoSupport.findForList(mapper + "list", pd);
            for(PageData driverUser : list){
                PageData driver = findDriverByUserID(driverUser.get("user_id").toString());
                driverUser.put("driver",driver);
            }
        }else{
            List<PageData> driverList = (List<PageData>) daoSupport.findForList("UserDriverMapper.list", pd);
            for(PageData driver : driverList){
                driver.put("role_id",4);
                PageData driverUser = (PageData)daoSupport.findForObject(mapper + "list",driver);
                if(driverUser != null){
                    driverUser.put("driver",driver);
                    list.add(driverUser);
                }
            }
        }
        return list;
    }

    /**
     *
     * @param pd
     * @return
     * @throws Exception
     */
    private boolean checkDriverInfo(PageData pd) throws Exception {
        boolean searchType = true;

        if(pd.get("driver_id") == null || "".equals(pd.get("driver_id"))){
            pd.remove("driver_id");
        }else{
            searchType = false;
        }
        if(pd.get("user_id") == null || "".equals(pd.get("user_id"))){
            pd.remove("user_id");
        }else{
            searchType = false;
        }
        if(pd.get("carrier_id") == null || "".equals(pd.get("carrier_id"))){
            pd.remove("carrier_id");
        }else{
            searchType = false;
        }
        if(pd.get("server_credit_point") == null || "".equals(pd.get("server_credit_point"))){
            pd.remove("server_credit_point");
        }else{
            searchType = false;
        }
        if(pd.get("server_credit_earned") == null || "".equals(pd.get("server_credit_earned"))){
            pd.remove("server_credit_earned");
        }else{
            searchType = false;
        }
        if(pd.get("car_brand") == null || "".equals(pd.get("car_brand"))){
            pd.remove("car_brand");
        }else{
            searchType = false;
        }
        if(pd.get("car_type") == null || "".equals(pd.get("car_type"))){
            pd.remove("car_type");
        }else{
            searchType = false;
        }
        if(pd.get("car_plate") == null || "".equals(pd.get("car_plate"))){
            pd.remove("car_plate");
        }else{
            searchType = false;
        }
        if(pd.get("car_year") == null || "".equals(pd.get("car_year"))){
            pd.remove("car_year");
        }else{
            searchType = false;
        }
        if(pd.get("car_fuel") == null || "".equals(pd.get("car_fuel"))){
            pd.remove("car_fuel");
        }else{
            searchType = false;
        }
        if(pd.get("car_cost") == null || "".equals(pd.get("car_cost"))){
            pd.remove("car_cost");
        }else{
            searchType = false;
        }
        if(pd.get("car_seat") == null || "".equals(pd.get("car_seat"))){
            pd.remove("car_seat");
        }else{
            searchType = false;
        }
        if(pd.get("car_km") == null || "".equals(pd.get("car_km"))){
            pd.remove("car_km");
        }else{
            searchType = false;
        }
        if(pd.get("driver_lic") == null || "".equals(pd.get("driver_lic"))){
            pd.remove("driver_lic");
        }else{
            searchType = false;
        }

        if(pd.get("bus_driver_lic") == null || "".equals(pd.get("bus_driver_lic"))){
            pd.remove("bus_driver_lic");
        }else{
            searchType = false;
        }

        if(pd.get("insur_type") == null || "".equals(pd.get("insur_type"))){
            pd.remove("insur_type");
        }else{
            searchType = false;
        }

        if(pd.get("servers_status") == null || "".equals(pd.get("servers_status"))){
            pd.remove("servers_status");
        }else{
            searchType = false;
        }
        if(pd.get("reject") == null || "".equals(pd.get("reject"))){
            pd.remove("reject");
        }else{
            searchType = false;
        }


        if(pd.get("reject_time_select") == null || "".equals(pd.get("reject_time_select"))){
            pd.remove("reject_time_select");
        }else{
            searchType = false;
            //拆分时间范围到搜索条件
            splitRangeTimeAndPushToSearch(pd,"reject_time_select","yyyy-MM-dd HH:mm:ss","reject_time_start","reject_time_end");
        }

        if(pd.get("insur_expired_select") == null || "".equals(pd.get("insur_expired_select"))){
            pd.remove("insur_expired_select");
        }else{
            searchType = false;
            splitRangeTimeAndPushToSearch(pd,"insur_expired_select","yyyy-MM-dd HH:mm:ss","insur_expired_start","insur_expired_end");
        }

        if(pd.get("driver_lic_expired_select") == null || "".equals(pd.get("driver_lic_expired_select"))){
            pd.remove("driver_lic_expired_select");
        }else{
            searchType = false;
            splitRangeTimeAndPushToSearch(pd,"driver_lic_expired_select","yyyy-MM-dd HH:mm:ss","driver_lic_expired_start","driver_lic_expired_end");
        }
        if(pd.get("bus_driver_lic_expired_select") == null || "".equals(pd.get("bus_driver_lic_expired_select"))){
            pd.remove("bus_driver_lic_expired_select");
        }else{
            searchType = false;
            splitRangeTimeAndPushToSearch(pd,"bus_driver_lic_expired_select","yyyy-MM-dd HH:mm:ss","bus_driver_lic_expired_start","bus_driver_lic_expired_end");
        }
        return searchType;
    }

    /**
     *
     * @param pd                PageData
     * @param rangeTime         需要拆分的时间范围字符串
     * @param format            日期格式
     * @param startTime         push到pd中的组装搜索条件
     * @param endTime           push到pd中的组装搜索条件
     * @throws Exception
     */
    private void splitRangeTimeAndPushToSearch(PageData pd,String rangeTime, String format, String startTime, String endTime) throws Exception {
        String rangeTimeStr = pd.getString(rangeTime);
        String[] rangeTimeSplit = rangeTimeStr.split(" - ");
        Date start = DateUtil.formatString(rangeTimeSplit[0], format);
        Date end = DateUtil.formatString(rangeTimeSplit[1], format);
        pd.put(startTime,start);
        pd.put(endTime,end);
        pd.remove(rangeTime);
    }

    @Override
    public List<PageData> carrierList(PageData pd) throws Exception {
        pd.put("role_id",3);
        boolean searchType = checkCarrierInfo(pd);//承运商搜索条件非空过滤
        List<PageData> list = new ArrayList<>();
        //搜索条件非空判断 并根据是否有司机指定字段来判断 是以用户 还是司机表来作为基表查询
        if(searchType){
            list = (List<PageData>) daoSupport.findForList(mapper + "list", pd);
            for(PageData carrierUser : list){
                PageData carrier = findCarrierByUserID(carrierUser.get("user_id").toString());
                carrierUser.put("carrier",carrier);
            }
        }else{
            List<PageData> carrierList = (List<PageData>) daoSupport.findForList("UserCarrierMapper.list", pd);
            for(PageData carrier : carrierList){
                carrier.put("role_id",3);
                PageData carrierUser = (PageData)daoSupport.findForObject(mapper + "list",carrier);
                if(carrierUser != null){
                    carrierUser.put("carrier",carrier);
                    list.add(carrierUser);
                }
            }
        }
        return list;
    }

    private boolean checkCarrierInfo(PageData pd) throws Exception {
        boolean searchType = true;

        if(pd.get("carrier_id") == null || "".equals(pd.get("carrier_id"))){
            pd.remove("carrier_id");
        }else{
            searchType = false;
        }
        if(pd.get("user_id") == null || "".equals(pd.get("user_id"))){
            pd.remove("user_id");
        }else{
            searchType = false;
        }
        if(pd.get("carrier_name") == null || "".equals(pd.get("carrier_name"))){
            pd.remove("carrier_name");
        }else{
            searchType = false;
        }
        if(pd.get("server_credit_point") == null || "".equals(pd.get("server_credit_point"))){
            pd.remove("server_credit_point");
        }else{
            searchType = false;
        }
        if(pd.get("server_credit_earned") == null || "".equals(pd.get("server_credit_earned"))){
            pd.remove("server_credit_earned");
        }else{
            searchType = false;
        }
        if(pd.get("carrier_lic") == null || "".equals(pd.get("carrier_lic"))){
            pd.remove("carrier_lic");
        }else{
            searchType = false;
        }

        if(pd.get("servers_status") == null || "".equals(pd.get("servers_status"))){
            pd.remove("servers_status");
        }else{
            searchType = false;
        }
        if(pd.get("reject") == null || "".equals(pd.get("reject"))){
            pd.remove("reject");
        }else{
            searchType = false;
        }


        if(pd.get("reject_time_select") == null || "".equals(pd.get("reject_time_select"))){
            pd.remove("reject_time_select");
        }else{
            searchType = false;
            //拆分时间范围到搜索条件
            splitRangeTimeAndPushToSearch(pd,"reject_time_select","yyyy-MM-dd HH:mm:ss","reject_time_start","reject_time_end");
        }

        if(pd.get("carrier_lic_expired_select") == null || "".equals(pd.get("carrier_lic_expired_select"))){
            pd.remove("carrier_lic_expired_select");
        }else{
            searchType = false;
            splitRangeTimeAndPushToSearch(pd,"carrier_lic_expired_select","yyyy-MM-dd HH:mm:ss","carrier_lic_expired_start","carrier_lic_expired_end");
        }


        return searchType;
    }

    @Override
    public PageData findById(String user_id) throws Exception {
        PageData pd = new PageData();
        pd.put("user_id",user_id);
        return (PageData) daoSupport.findForObject(mapper+"findById", pd);
    }

    @Override
    public List<PageData> findByEmail(String user_email) throws Exception {

        PageData findEmail = new PageData();
        findEmail.put("user_email",user_email);
//        System.out.println("user_email="+user_email);
        List<PageData> list = (List<PageData>) daoSupport.findForList(mapper+"list",findEmail);
//        System.out.println("list="+list);
        return list;
    }

    @Override
    public List<PageData> findByPhone(String phone) throws Exception {
        PageData findPhone = new PageData();
        findPhone.put("phone",phone);
        List<PageData> list = (List<PageData>) daoSupport.findForList(mapper+"findByPhone",findPhone);
        if(list.size() == 0){
//            System.err.println("UserServiceImpl.findByPhone");
//            System.err.println("查询电话"+phone+"无记录!");
            throw new ServiceException("查询电话"+phone+"无记录!");
        }
        PageData currentUser = list.get(0);
//        System.err.println("currentUser = " + currentUser);
        return list;
    }


    @Override
    public int deleteAll(String[] DATA_IDS) throws Exception {

        return (int)daoSupport.batchDelete(mapper+"deleteAll", DATA_IDS);
    }



    /**
     * 通过用户id查询[承运商]角色的附加数据
     * @param user_id
     * @return
     */
    @Override
    public PageData findCarrierByUserID(String user_id) throws Exception {
        PageData carrier = new PageData();
        carrier.put("user_id",user_id);
        carrier = (PageData) daoSupport.findForObject("UserCarrierMapper.list",carrier);
        return carrier;
    }

    /**
     * 通过用户id查询[司机]角色的附加数据
     * @param user_id
     * @return
     */
    @Override
    public PageData findDriverByUserID(String user_id) throws Exception {
        PageData driver = new PageData();
        driver.put("user_id",user_id);
        driver = (PageData) daoSupport.findForObject("UserDriverMapper.list",driver);

        if(driver == null){
            //如果角色是司机 但是司机表没有任何一条数据 则新增一条司机默认值数据插入到表中 方便后续更新编辑操作
            driver = new PageData();
            driver.put("driver_id",user_id);
            driver.put("user_id",user_id);
            driver.put("server_credit_point",0);//司机的积分
            driver.put("server_credit_earned",0);//游客信用 由司机对游客的评价

            int count = (int) daoSupport.save("UserDriverMapper.save",driver);
            if(count != 1){
                throw new ServiceException("新增旧用户司机数据失败!");
            }else{
                findDriverByUserID(user_id);
            }
        }

        if(driver!=null && driver.get("carrier_id")!=null && driver.get("carrier_id").toString().length() > 30){
            PageData carrier = (PageData) findCarrierByUserID(driver.getString("carrier_id"));
            driver.put("carrier_name",carrier.get("carrier_name"));
        }
        return driver;
    }

    /**
     * 通过用户id查询[游客]角色的附加数据
     * @param user_id
     * @return
     */
    @Override
    public PageData findGuestByUserID(String user_id) throws Exception {
        PageData guest = new PageData();
        guest.put("user_id",user_id);
        guest = (PageData) daoSupport.findForObject("UserGuestMapper.list",guest);
        return guest;
    }

    @Override
    public Set<String> findPermissionsByRoleID(Integer role_id)throws Exception  {
        List<String> permissionsList= (List<String>)daoSupport.findForList(mapper+"findPermissionsByRoleID", role_id);
        Set result = new HashSet(permissionsList);
        return result;
    }

    @Override
    public Set<String> findRolesByPhone(String phone)throws Exception {

        List<String> rolesList= (List<String>)daoSupport.findForList(mapper+"findRolesByPhone", phone);
        Set result = new HashSet(rolesList);
        return result;
    }

    @Override
    public Integer findRoleIDByPhone(String phone) throws Exception {
        Integer role_id = (Integer)daoSupport.findForObject(mapper+"findRoleIDByPhone", phone);
        return role_id;
    }

    @Override
    public String getEmailByUserID(String user_id) throws Exception {
        if(user_id == null && StringUtils.isNotBlank(user_id)){
            throw new ServiceException("通过用户ID获取用户邮箱失败:user_id不能为空!");
        }
        String userEmail = (String)daoSupport.findForObject(mapper+"getEmailByUserID", user_id);
        if(userEmail != null && StringUtils.isNotBlank(userEmail)){
            if(!EmailUtil.isEmail(userEmail)){
                throw new ServiceException("用户邮箱格式不正确!userEmail="+userEmail);
            }
        }else {
            throw new ServiceException("用户邮箱不正确!userEmail="+userEmail);
        }
        return userEmail;
    }

    /**
     * 通过订单ID查询该订单的服务人员信息
     * 如果订单为
     *      内部消化订单 管理员还未指定司机 则无服务人员信息
     *      竞拍订单 竞拍成功情况下 返回服务人员信息为 竞拍成功人的信息
     *          服务人员角色为 司机
     *          服务人员角色为 承运商
     * @param order_id
     * @return
     * @throws Exception
     */
    @Override
    public PageData getServicePersonal(Integer order_id) throws Exception {
        PageData pd = new PageData();
        pd.put("order_id",order_id);
        pd.put("has_success",1);
        List<PageData> list = cuctionService.list(pd);
        if(list.size() > 0){
            PageData auction = list.get(0);
            pd.put("auction",auction);

            String user_id = auction.getString("server_user_id");
            PageData servicePersonal = parseUserInfo(findById(user_id));
            pd.put("servicePersonal",servicePersonal);

            return pd;
        }else{
            return null;
        }
    }
    /**
     * 转换用户信息
     * 去除敏感数据 并封装角色属性相应的数据
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData parseUserInfo(PageData pd) throws Exception {
        //去除敏感数据
        //移除Session中不要的用户的数据
        pd.remove("password");
        pd.remove("salt");
        pd.remove("create_time");
        pd.remove("create_ip");
        pd.remove("update_time");
        pd.remove("last_login_time");
        pd.remove("last_login_ip");

        //判断用户角色 返回对应角色附加数据
        int role_id = Integer.parseInt(pd.get("role_id").toString());
        switch(role_id) {
            case 1:
                //SuperAdmin-超级管理员;
                break;
            case 2:
                //Admin-管理员;
                break;
            case 3:
                //Carrier-承运商;
                PageData carrier = findCarrierByUserID(pd.get("user_id").toString());
                pd.put("carrier",carrier);
                break;
            case 4:
                //Driver-司机;
                PageData driver = findDriverByUserID(pd.get("user_id").toString());
                pd.put("driver",driver);
                break;
//            case 5:
//                //Guest-游客;
//                PageData guest = userService.findGuestByUserID(currentUser.get("user_id").toString());
//                currentUser.put("guest",guest);
//                break;
            default:
                //...;
                break;
        }

        return pd;
    }

    /**
     * 旧用户数据补全
     * @param pageData
     * @return 成功返回1
     * @throws Exception
     */
    @Override
    public int oldUserInfoSupplement(PageData pageData) throws Exception {
        //获取session中的
        PageData oldUser = getOldUser();
        if(oldUser == null){
            throw new ServiceException("旧用户数据更新提交失败:登陆已过期,请重新登录!");
        }
        oldUser.put("status",2);
        oldUser.put("old_status",2);
        oldUser.put("avatar",pageData.get("avatar"));
        oldUser.put("user_email",pageData.get("user_email"));

        //如果旧用户是司机 还需新增司机附加信息
        Integer role_id = oldUser.getInt("role_id");
        if(role_id == 4){
            //通过当前oldUser的用户id查询司机附件表 如果不存在司机附加信息 执行新增  如果已经存在 则无需任何操作
            PageData driver = findDriverByUserID(oldUser.get("user_id").toString());
//            System.err.println("司机附加数据: "+driver);
            if(driver == null){
                //Driver-司机;
                driver = new PageData();
                driver.put("driver_id",oldUser.get("user_id"));
                driver.put("user_id",oldUser.get("user_id"));
                driver.put("server_credit_point",0);//司机的积分
                driver.put("server_credit_earned",0);//游客信用 由司机对游客的评价
                int count = (int) daoSupport.save("UserDriverMapper.save", driver);
                if(count != 1){
                    throw new ServiceException("新增旧用户司机数据失败!");
                }else{
//                    System.err.println("新增旧用户司机数据成功! ");
                }
            }
        }

        return (int) daoSupport.update(mapper+"edit", oldUser);
    }

    @Override
    public void changeServersStatus(PageData pageData) throws Exception {

        PageData pd = new PageData();

        if(pageData.get("role_id") ==null || "".equals(pageData.get("role_id").toString())  ){
            throw new ServiceException("role_id不能空");
        }
        if(pageData.get("user_id") ==null || "".equals(pageData.get("user_id").toString())  ){
            throw new ServiceException("user_id不能空");
        }
        if(pageData.get("servers_status") ==null || "".equals(pageData.get("servers_status").toString())  ){
            throw new ServiceException("servers_status不能空");
        }
        if(pageData.getInt("servers_status") != 0 && pageData.getInt("servers_status") != 1 ){
            throw new ServiceException("servers_status参数错误");
        }

        Integer role_id = pageData.getInt("role_id");
        Integer servers_status = pageData.getInt("servers_status");
        String user_id = pageData.getString("user_id");
        pd.put("user_id",user_id);
        pd.put("servers_status",pageData.get("servers_status"));

        if(servers_status == 0){//驳回
            pd.put("reject",pageData.get("email_msg"));
            pd.put("reject_time",new Date());
        }else if(servers_status == 1){//通过
            //验证数据完整性
            checkedServicePersonalInfo(role_id,user_id);

        }

        switch (role_id){
            case 3://承运商
                daoSupport.update("UserCarrierMapper.edit", pd);
                break;

            case 4://司机
                daoSupport.update("UserDriverMapper.edit", pd);
                break;

        }
    }



    /**
     * 验证司机、承运商数据完整性
     * @param role_id
     * @param user_id
     */
    private void checkedServicePersonalInfo(Integer role_id, String user_id) throws Exception {
        PageData pd = null;
        switch (role_id){
            case 3://承运商
                pd = (PageData)daoSupport.findForObject("UserCarrierMapper.findById", user_id);
                break;

            case 4://司机
                pd = (PageData)daoSupport.findForObject("UserDriverMapper.findById", user_id);
                break;
        }
//        System.err.println("pd = " + pd);
        if(pd == null){
            throw new ServiceException("资料信息不全,请补全信息,并提交更新之后,在执行此操作!");
        }else{
            switch (role_id){
                case 3://承运商
                    if(pd.get("carrier_name") ==null || "".equals(pd.get("carrier_name").toString())  ){
                        throw new ServiceException("carrier_name承运商名称不能为空");
                    }
                    if(pd.get("carrier_lic") ==null || "".equals(pd.get("carrier_lic").toString())  ){
                        throw new ServiceException("carrier_lic承运商营业执照不能为空");
                    }
                    if(pd.get("carrier_lic_img1") ==null || "".equals(pd.get("carrier_lic_img1").toString())  ){
                        throw new ServiceException("carrier_lic_img1承运商营业执照正面照未上传");
                    }
                    if(pd.get("carrier_lic_img2") ==null || "".equals(pd.get("carrier_lic_img2").toString())  ){
                        throw new ServiceException("carrier_lic_img2承运商营业执照反面照未上传");
                    }
                    if(pd.get("carrier_lic_expired") ==null || "".equals(pd.get("carrier_lic_expired").toString())  ){
                        throw new ServiceException("carrier_lic_expired承运商营业执照过期日不能为空");
                    }


                    break;

                case 4://司机
                    if(pd.get("car_brand") ==null || "".equals(pd.get("car_brand").toString())  ){
                        throw new ServiceException("car_brand车-品牌不能为空");
                    }
                    /*if(pd.get("car_type") ==null || "".equals(pd.get("car_type").toString())  ){
                        throw new ServiceException("car_type车-类型不能为空");
                    }*/
                    if(pd.get("car_plate") ==null || "".equals(pd.get("car_plate").toString())  ){
                        throw new ServiceException("car_plate车牌号不能为空");
                    }
                    if(pd.get("car_year") ==null || "".equals(pd.get("car_year").toString())  ){
                        throw new ServiceException("car_year车龄不能为空");
                    }
                    if(pd.get("car_fuel") ==null || "".equals(pd.get("car_fuel").toString())  ){
                        throw new ServiceException("car_fuel燃油、油耗不能为空");
                    }
                    if(pd.get("car_cost") ==null || "".equals(pd.get("car_cost").toString())  ){
                        throw new ServiceException("car_cost每公里的用车成本不能为空");
                    }
                    if(pd.get("car_seat") ==null || "".equals(pd.get("car_seat").toString())  ){
                        throw new ServiceException("car_seat车的座位数量不能为空");
                    }
                    if(pd.get("car_seat") ==null || "".equals(pd.get("car_seat").toString())  ){
                        throw new ServiceException("car_seat车的座位数量不能为空");
                    }
                    if(pd.get("car_km") ==null || "".equals(pd.get("car_km").toString())  ){
                        throw new ServiceException("car_km公里数不能为空");
                    }
                    if(pd.get("driver_lic") ==null || "".equals(pd.get("driver_lic").toString())  ){
                        throw new ServiceException("driver_lic驾照号不能为空");
                    }
                    if(pd.get("driver_lic_img1") ==null || "".equals(pd.get("driver_lic_img1").toString())  ){
                        throw new ServiceException("driver_lic_img1驾照正面照未上传");
                    }
                    if(pd.get("driver_lic_img2") ==null || "".equals(pd.get("driver_lic_img2").toString())  ){
                        throw new ServiceException("driver_lic_img2驾照正面照未上传");
                    }
                    if(pd.get("driver_lic_expired") ==null || "".equals(pd.get("driver_lic_expired").toString())  ){
                        throw new ServiceException("driver_lic_expired驾照过期日不能为空");
                    }



                    break;
            }
        }

    }


    /**
     * 	 对密码进行加密
     * @param password 原始密码
     * @param salt 盐值
     * @return 加密后的密码
     */
    private static String getMd5Password(String password,String salt) {
        // salt+password+salt 进行3次加密
        String msg=salt+password+salt;
        for(int i=0;i<3;i++) {
            msg= DigestUtils.md5DigestAsHex(msg.getBytes());
        }
        return msg;
    }


    /**
     * 验证用户必填项
     * @param pd
     */
    private void checkUserInfo(PageData pd){
//        System.err.println("UserServiceImpl.checkUserInfo:start");
        if( pd.get("user_email") ==null ||"".equals(pd.get("user_email").toString())){
            throw new ServiceException("用户注册异常:Email不能空");
        }
        if(pd.get("role_id") ==null || "".equals(pd.get("role_id").toString())  ){
            throw new ServiceException("用户注册异常:role_id不能空");
        }
        if(pd.get("password") ==null || "".equals(pd.get("password").toString())  ){
            throw new ServiceException("用户注册异常:password不能空");
        }
        if( pd.get("phone") ==null  || "".equals(pd.get("phone").toString())){
            throw new ServiceException("用户注册异常:phone不能空");
        }
        /*if(pd.get("sex") ==null || "".equals(pd.get("sex").toString())){
            throw new ServiceException("用户注册异常:sex不能空");
        }*/
        /*if(pd.get("avatar") ==null|| "".equals(pd.get("avatar").toString()) ){
            throw new ServiceException("用户注册异常:avatar不能空");
        }*/
//        System.err.println("UserServiceImpl.checkUserInfo:end");
    }



    private PageData getCurrentUser(){
        return (PageData) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
    }
    private PageData getOldUser(){
        return (PageData) SecurityUtils.getSubject().getSession().getAttribute("oldUser");
    }
    private String getCurrentUserID(){
        PageData pd = (PageData) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
        String user_id = pd.get("user_id").toString();
        return user_id;

    }
}
